<template>
	<view class="register-container">
		<!-- 顶部Logo和系统名称 -->
		<view class="header register-container-item">
			<image class="logo" src="/static/logo_2.0.jpg"></image>
			<text class="system-name">旭荣网盾(GDCS)</text>
		</view>
		
		<!-- 注册表单卡片 -->
		<view class="register-card register-container-item">
			<view class="card-title">用户注册</view>
			
			<!-- 邮箱输入框 -->
			<view class="input-group" :class="{ 'error': emailError }">
				<image class="input-icon" src="/static/Email.png"></image>
				<input 
					class="input-field" 
					type="text" 
					placeholder="请输入邮箱地址" 
					v-model="email"
					@blur="validateEmail"
				/>
			</view>
			<view class="error-text" v-if="emailError">{{ emailError }}</view>
			
			<!-- 用户名输入框 -->
			<view class="input-group">
				<image class="input-icon" src="/static/user_name.png"></image>
				<input 
					class="input-field" 
					type="text" 
					placeholder="设置用户名（可选，未设置将使用邮箱前缀）" 
					v-model="user_name"
				/>
			</view>
			
			<!-- 密码输入框 -->
			<view class="input-group" :class="{ 'error': passwordError }">
				<image class="input-icon" src="/static/Password.png"></image>
				<input 
					class="input-field" 
					:type="showPassword ? 'text' : 'password'" 
					placeholder="请设置密码（至少6位）" 
					v-model="password"
					@blur="validatePassword"
				/>
				<image 
					class="password-toggle" 
					:src="showPassword ? '/static/eye-open.png' : '/static/eye-close.png'"
					@click="togglePassword"
					v-if="password"
				/>
			</view>
			<view class="error-text" v-if="passwordError">{{ passwordError }}</view>
			<view class="password-strength" v-if="password">
				<view class="strength-bar">
					<view class="strength-fill" :class="passwordStrengthClass" :style="{ width: passwordStrength + '%' }"></view>
				</view>
				<text class="strength-text">{{ passwordStrengthText }}</text>
			</view>
			
			<!-- 确认密码输入框 -->
			<view class="input-group" :class="{ 'error': confirmPasswordError }">
				<image class="input-icon" src="/static/Password.png"></image>
				<input 
					class="input-field" 
					type="password" 
					placeholder="请确认密码" 
					v-model="confirmPassword"
					@blur="validateConfirmPassword"
				/>
			</view>
			<view class="error-text" v-if="confirmPasswordError">{{ confirmPasswordError }}</view>
			
			<!-- 验证码输入框 -->
			<view class="input-group" :class="{ 'error': verificationCodeError }">
				<image class="input-icon" src="/static/Notice.png"></image>
				<input 
					class="input-field" 
					type="text" 
					placeholder="请输入验证码" 
					v-model="verificationCode"
					@blur="validateVerificationCode"
				/>
				<button 
					class="send-code-btn" 
					:disabled="!canSendCode || isSendingCode" 
					@click="sendVerificationCode"
				>
					{{ isSendingCode ? '发送中...' : (countdown > 0 ? `${countdown}s后重试` : '发送验证码') }}
				</button>
			</view>
			<view class="error-text" v-if="verificationCodeError">{{ verificationCodeError }}</view>
			
			<!-- 用户协议 -->
			<view class="agreement">
				<label class="agreement-checkbox">
					<view class="checkbox-custom" @click="toggleAgreeTerms">
						<image :src="agreeTerms ? '/static/gxk_yes.png' : '/static/gxk_no-.png'" mode="aspectFit" class="checkbox-icon" />
					</view>
					<text>我已阅读并同意</text>
					<text class="agreement-link" @click="showTerms">《用户协议》</text>
					<text>和</text>
					<text class="agreement-link" @click="showPrivacy">《隐私政策》</text>
				</label>
			</view>
			
			<!-- 注册按钮 -->
			<button class="register-btn" @click="handleRegister" :disabled="!agreeTerms">注册</button>
			
			<!-- 登录链接 -->
			<view class="login-link">
				<text>已有账户？</text>
				<text class="login-text" @click="goToLogin">立即登录</text>
			</view>
		</view>
		
		<!-- 注册成功提示模态框 -->
		<view class="modal" v-if="showSuccessModal" @click="closeSuccessModal">
			<view class="modal-content" @click.stop>
				<view class="modal-title">注册成功</view>
				<view class="modal-message">
					恭喜您注册成功！请使用邮箱和密码登录系统。
				</view>
				<button class="modal-btn" @click="goToLogin">去登录</button>
			</view>
		</view>
		
		<!-- 错误提示模态框 -->
		<view class="modal" v-if="showErrorModal" @click="closeErrorModal">
			<view class="modal-content" @click.stop>
				<view class="modal-title">注册失败</view>
				<view class="modal-message">{{ errorMessage }}</view>
				<button class="modal-btn" @click="closeErrorModal">确定</button>
			</view>
		</view>
	</view>
</template>

<script>
	import { register, sendVerificationCode } from '../../api/api.js';
	export default {
		data() {
			return {
				email: '',
				user_name: '',
				password: '',
				confirmPassword: '',
				agreeTerms: false,
				showSuccessModal: false,
				showErrorModal: false,
				errorMessage: '',
				showPassword: false,
				emailError: '',
				passwordError: '',
				confirmPasswordError: '',
				verificationCode: '',
				verificationCodeError: '',
				passwordStrength: 0,
				passwordStrengthClass: '',
				passwordStrengthText: '',
				countdown: 0,
				countdownTimer: null,
				isSendingCode: false
			}
		},
		onLoad() {

		},
		computed: {
			// 是否可以发送验证码
			canSendCode() {
				return this.countdown === 0 && this.email && !this.emailError && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email);
			}
		},
		methods: {
		handleRegister() {
			// 清除之前的错误信息
			this.clearErrors();
			
			// 验证所有字段
			if (!this.validateAll()) {
				return;
			}
			
			// 调用注册API，传入用户输入的用户名
			register(this.email, this.password, this.verificationCode, this.user_name)
				.then((res) => {
					if (res.success) {
						// 注册成功
						this.showSuccessModal = true;
					} else {
						// 注册失败
						this.showError(res.message || '注册失败，请稍后重试');
					}
				})
				.catch((error) => {
					this.showError(error.message || '注册失败，请检查网络连接');
				});
		},
		
		validateAll() {
			let isValid = true;
			
			// 验证邮箱
			if (!this.validateEmail()) {
				isValid = false;
			}
			
			// 验证密码
			if (!this.validatePassword()) {
				isValid = false;
			}
			
			// 验证确认密码
			if (!this.validateConfirmPassword()) {
				isValid = false;
			}
			
			// 验证验证码
			if (!this.validateVerificationCode()) {
				isValid = false;
			}
			
			// 验证用户名
			if (this.user_name && this.user_name.length < 2) {
				this.showError('用户名长度至少2位');
				isValid = false;
			}
			
			// 验证协议
			if (!this.agreeTerms) {
				this.showError('请先同意用户协议和隐私政策');
				isValid = false;
			}
			
			return isValid;
		},
		
		validateEmail() {
			const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
			if (!this.email) {
				this.emailError = '请输入邮箱地址';
				return false;
			} else if (!emailRegex.test(this.email)) {
				this.emailError = '请输入有效的邮箱地址';
				return false;
			} else {
				this.emailError = '';
				return true;
			}
		},
			
		validatePassword() {
			if (!this.password) {
				this.passwordError = '请输入密码';
				return false;
			} else if (this.password.length < 6) {
				this.passwordError = '密码长度至少6位';
				return false;
			} else {
				this.passwordError = '';
				this.calculatePasswordStrength();
				return true;
			}
		},
			
		validateConfirmPassword() {
			if (!this.confirmPassword) {
				this.confirmPasswordError = '请确认密码';
				return false;
			} else if (this.password !== this.confirmPassword) {
				this.confirmPasswordError = '两次输入的密码不一致';
				return false;
			} else {
				this.confirmPasswordError = '';
				return true;
			}
		},
		
		// 验证验证码
		validateVerificationCode() {
			if (!this.verificationCode) {
				this.verificationCodeError = '请输入验证码';
				return false;
			} else if (!/^\d+$/.test(this.verificationCode)) {
				this.verificationCodeError = '验证码只能包含数字';
				return false;
			} else {
				this.verificationCodeError = '';
				return true;
			}
		},
		
		// 发送验证码
		sendVerificationCode() {
			// 先验证邮箱
			if (!this.validateEmail()) {
				this.showError('请输入有效的邮箱地址');
				return;
			}

			this.isSendingCode = true;
			sendVerificationCode(this.email)
				.then((res) => {
					if (res.code === 0 || res.success) {
						// 验证码发送成功，开始倒计时
						this.startCountdown();
						uni.showToast({
							title: '验证码发送成功，请查收邮件',
							icon: 'success'
						});
					} else {
						this.showError(res.msg || '验证码发送失败，请稍后重试');
					}
				})
				.catch((error) => {
					this.showError(error.message || '验证码发送失败，请检查网络连接');
				})
				.finally(() => {
					this.isSendingCode = false;
				});
		},
		
		// 开始倒计时
		startCountdown() {
			this.countdown = 60;
			if (this.countdownTimer) {
				clearInterval(this.countdownTimer);
			}
			this.countdownTimer = setInterval(() => {
				this.countdown--;
				if (this.countdown <= 0) {
					clearInterval(this.countdownTimer);
				}
			}, 1000);
		},
			
			calculatePasswordStrength() {
				let strength = 0;
				let text = '';
				let className = '';
				
				if (this.password.length >= 6) strength += 20;
				if (this.password.length >= 8) strength += 20;
				if (/[a-z]/.test(this.password)) strength += 20;
				if (/[A-Z]/.test(this.password)) strength += 20;
				if (/[0-9]/.test(this.password)) strength += 10;
				if (/[^A-Za-z0-9]/.test(this.password)) strength += 10;
				
				if (strength < 40) {
					text = '弱';
					className = 'weak';
				} else if (strength < 70) {
					text = '中等';
					className = 'medium';
				} else {
					text = '强';
					className = 'strong';
				}
				
				this.passwordStrength = strength;
				this.passwordStrengthText = text;
				this.passwordStrengthClass = className;
			},
			
			togglePassword() {
				this.showPassword = !this.showPassword;
			},
			
			toggleAgreeTerms() {
				this.agreeTerms = !this.agreeTerms;
			},
			
			clearErrors() {
				this.emailError = '';
				this.passwordError = '';
				this.confirmPasswordError = '';
				this.verificationCodeError = '';
			},
			
			showError(message) {
				this.errorMessage = message;
				this.showErrorModal = true;
			},
			
			closeErrorModal() {
				this.showErrorModal = false;
			},
			
			closeSuccessModal() {
				this.showSuccessModal = false;
			},
			
			goToLogin() {
				uni.navigateBack();
			},
			
			showTerms() {
				uni.showToast({
					title: '用户协议功能待开发',
					icon: 'none'
				});
			},
			
			showPrivacy() {
				uni.showToast({
					title: '隐私政策功能待开发',
					icon: 'none'
				});
			}
		},
		// 组件销毁时清除定时器
		destroyed() {
			if (this.countdownTimer) {
				clearInterval(this.countdownTimer);
			}
		}
}
</script>

<style>
	.register-container {
		min-height: 100vh;
		background: url('/static/home.webp') center center / cover no-repeat;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 80rpx 60rpx;
		position: relative;
	}

	.register-container::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.4);
		z-index: 1;
	}

	.register-container-item {
		position: relative;
		z-index: 2;
	}

	.header {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 60rpx;
	}

	.logo {
		width: 100rpx;
		height: 100rpx;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
	}

	.system-name {
		font-size: 40rpx;
		font-weight: bold;
		color: #ffffff;
		text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
	}

	.register-card {
		background: #ffffff;
		border-radius: 24rpx;
		padding: 50rpx 40rpx;
		width: 100%;
		max-width: 600rpx;
		box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
	}

	.card-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		text-align: center;
		margin-bottom: 40rpx;
	}

	.input-group {
		display: flex;
		align-items: center;
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 20rpx 24rpx;
		margin-bottom: 24rpx;
		border: 2rpx solid #e9ecef;
		transition: border-color 0.3s;
	}

	.input-group:focus-within {
		border-color: #667eea;
	}

	.input-group.error {
		border-color: #e74c3c;
	}

	.input-icon {
		width: 28rpx;
		height: 28rpx;
		margin-right: 16rpx;
		opacity: 0.6;
	}

	.input-field {
		flex: 1;
		font-size: 26rpx;
		color: #333333;
		background: transparent;
		border: none;
		outline: none;
	}

	.password-toggle {
		width: 24rpx;
		height: 24rpx;
		opacity: 0.6;
		margin-left: 16rpx;
	}

	.error-text {
		font-size: 22rpx;
		color: #e74c3c;
		margin-top: -20rpx;
		margin-bottom: 20rpx;
		margin-left: 8rpx;
	}

	.password-strength {
		margin-top: -20rpx;
		margin-bottom: 20rpx;
	}

	.strength-bar {
		height: 6rpx;
		background: #e9ecef;
		border-radius: 3rpx;
		overflow: hidden;
		margin-bottom: 8rpx;
	}

	.strength-fill {
		height: 100%;
		transition: width 0.3s, background-color 0.3s;
	}

	.strength-fill.weak {
		background: #e74c3c;
	}

	.strength-fill.medium {
		background: #f39c12;
	}

	.strength-fill.strong {
		background: #27ae60;
	}

	.strength-text {
		font-size: 20rpx;
		color: #666666;
	}

	.agreement {
		margin-bottom: 30rpx;
	}

	.agreement-checkbox {
		display: flex;
		align-items: center;
		font-size: 24rpx;
		color: #666666;
		line-height: 1.4;
	}

	.checkbox-custom {
		width: 32rpx;
		height: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 10rpx;
	}

	.checkbox-icon {
		width: 32rpx;
		height: 32rpx;
	}

	.agreement-link {
		color: #667eea;
		text-decoration: underline;
		margin: 0 4rpx;
	}

	.register-btn {
		width: 100%;
		height: 80rpx;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: #ffffff;
		font-size: 30rpx;
		font-weight: bold;
		border: none;
		border-radius: 12rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
		transition: transform 0.2s;
	}

	.register-btn:disabled {
		background: #cccccc;
		box-shadow: none;
	}

	.register-btn:active:not(:disabled) {
		transform: translateY(2rpx);
	}

	.login-link {
		text-align: center;
		font-size: 24rpx;
		color: #666666;
	}

	.login-text {
		color: #667eea;
		text-decoration: underline;
		margin-left: 10rpx;
	}

	.modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.modal-content {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 40rpx;
		margin: 0 60rpx;
		max-width: 500rpx;
		text-align: center;
	}

	.modal-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #27ae60;
		margin-bottom: 20rpx;
	}

	.modal-message {
		font-size: 24rpx;
		color: #666666;
		line-height: 1.6;
		margin-bottom: 30rpx;
	}

	.modal-btn {
		background: #667eea;
		color: #ffffff;
		border: none;
		border-radius: 8rpx;
		padding: 16rpx 40rpx;
		font-size: 26rpx;
	}
</style>
